package com.example.administrator.fangbook.importlocal.fragment.presenter;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;

import com.example.administrator.fangbook.HtlMvp.activity.BaseMvpPresenter;
import com.example.administrator.fangbook.importlocal.bean.FileNode;
import com.example.administrator.fangbook.importlocal.fragment.view.ImportLocalView;
import com.example.administrator.fangbook.importlocal.utils.ScanSdUtil;
import com.example.administrator.fangbook.utils.LogUtil;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ImportLocalPresenter extends BaseMvpPresenter<ImportLocalView> {
    private static final int START_SORT = 0x001;

    private ArrayList<FileNode> mFileNodes = new ArrayList<>();
    private FileSort mFileSortUtil = new FileSort();
    private ScanSdUtil mScanSdUtil;
    private SortHadlerThread mSortHadlerThread;

    /**
     * 开启排序和添加子线程
     */
    public void startSortToAddThread() {
        mSortHadlerThread = new SortHadlerThread();
    }

    /**
     * 开启扫描子线程
     */
    public void startScanThread() {
        mScanSdUtil = new ScanSdUtil(new ScanSdUtil.ScanSucceedLisener() {
            @Override
            public void scanSucceed(List<FileNode> results, FileNode currNode) {
                //主线程回调数据过来
//                    doData(results);
                if (mSortHadlerThread != null && mSortHadlerThread.isAlive()) {
                    mSortHadlerThread.startSort(results);
                }
            }
        });
    }

    /**
     * 开始扫描
     *
     * @param fileNode
     */
    public void startScan(FileNode fileNode) {
        if (mScanSdUtil == null || fileNode == null) {
            return;
        }
        mScanSdUtil.scanFiles(fileNode);
    }


    class SortHadlerThread extends HandlerThread {

        private FileSortHander mFileSortHander;

        public SortHadlerThread() {
            super("sort_thread", Thread.NORM_PRIORITY);
            start();
            if (getLooper() != null) {
                mFileSortHander = new FileSortHander(this, getLooper());
            }
        }

        public void startSort(List<FileNode> nodes) {
            if (nodes == null || nodes.size() == 0) {
                return;
            }
            Message mge = Message.obtain(mFileSortHander);
            mge.what = START_SORT;
            mge.obj = nodes;
            mFileSortHander.sendMessage(mge);
        }

        public void stopWork() {
            LogUtil.e("线程","SortHadlerThread--stopWork");
            mFileSortHander.removeCallbacksAndMessages(null);
            mFileSortHander = null;
            quit();
        }

        public void doSort(List<FileNode> fileNodes) {
            if (fileNodes == null || fileNodes.size() == 0) {
                return;
            }
            for (FileNode fileNode : fileNodes) {
                if (!mFileNodes.contains(fileNode)) {
                    mFileNodes.add(fileNode);
                }
            }
            fileNodes.clear();
            fileNodes = null;
            Collections.sort(mFileNodes, mFileSortUtil);
            //发送到主线程
            if (getView() != null) {
                getView().getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        getView().setAdapter(mFileNodes);
                    }
                });
            }
        }
    }


    private class FileSort implements Comparator<FileNode> {
        @Override
        public int compare(FileNode t0, FileNode t1) {
            if (t0.getFirstChar() == t1.getFirstChar()) {
                return 0;
            }
            if (t0.getFirstChar() == '#') {
                return 1;
            }
            if (t1.getFirstChar() == '#') {
                return -1;
            }
            return t0.getFirstChar() > t1.getFirstChar() ? 1 : -1;
        }
    }

    static class FileSortHander extends Handler {

        private WeakReference<SortHadlerThread> mOut;

        public FileSortHander(SortHadlerThread sortHadlerThread, Looper looper) {
            super(looper);
            mOut = new WeakReference<>(sortHadlerThread);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            SortHadlerThread sortHadlerThread = mOut.get();
            if (sortHadlerThread == null) {
                return;
            }
            switch (msg.what) {
                case START_SORT:
                    sortHadlerThread.doSort((List<FileNode>) msg.obj);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void destroyView() {
        if (mScanSdUtil != null)
            mScanSdUtil.stopWork();
        if (mSortHadlerThread != null)
            mSortHadlerThread.stopWork();
        mFileNodes.clear();
        mFileSortUtil = null;
        super.destroyView();
    }
}
